<?php

/**
 * Description of GoodsModel
 *
 * @author XIAYUANCHUAN
 */

namespace Qwadmin\Model;

use Think\Model;
use Qwadmin\Controller;

class GoodsModel extends Model {

    private $imageextarr = array('.png', ".jpg", ".gif");
    private $goodscheckGonfig = array(
        'pic_info_num' => 1, //商品banner
        'pic_thumb_num' => 1, //商品banner
        'pic_pc_num' => 2, //产品描述 pc
        'pic_mobile_num' => 2, //产品描述 mo
        'price_ok' => 0, //商品价格设置与否  
        'info_ok' => 0, // 其他必填驻点是否满足
        'oother_must_field' => array(
            'sku',
            'name',
            'price',
            'price_cost',
//            'price_trade',
//            'info_mobile',
//            'info_pc',
        ),
    );

    function __construct($name = '', $tablePrefix = '', $connection = '') {
        parent::__construct($name, $tablePrefix, $connection);
    }

    /**
     * 初始化goods信息到goods数组
     */
    function init_goods($goods_id) {

        ///初始化商品信息
        if (!$goods_id) {
            return FALSE;
        }
        $goods = M('goods')->where(array('id' => $goods_id))->find();
        ////获取商品状态
        if (!$goods) {
            return false;
        }
        $goods['status'] = M('goods_info')->where(array('goods_id' => $goods['id']))->find();
        ////产品分类绑定
        $goods['type_info'] = M('shop_types')->field('shop_sites_id,shop_type_id')->where(array('goods_type_id' => $goods['goods_type_id']))->select();
        $goods['type_info_key'] = array();
        if ($goods['type_info']) {
            foreach ($goods['type_info'] as $key => $vall) {
                $goods['type_info_key'][$vall['shop_sites_id']] = $vall['shop_type_id'];
            }
        }
        $goods['op'] = M('goods_op')->field('*')->where(array('goods_id' => $goods['id']))->select();


        /*
          $goods               商品详情
          $goods['status']     商品状态信息
          $goods['type_info']  商品分类分布
         */



        return $goods;
    }

    ///仅获取信息
    function get_img_bysku($sku) {

        $imgurl = "http://img01.shenghuigo.com/i.php?p=" . $sku;
        //echo $imgurl."<br>";
        //$ha=new \Qwadmin\Model\ApiModel();
        //$parm='';
        //$re=$ha->post($imgurl,$parm,60);

        $re = file_get_contents($imgurl);
        if ($re == false) {
            //$this->get_goods_img($goods_id);
            $re['rsp'] = 'error';
            $re['log'] = 'timeout_error :by network';
            return $re;
        } else {
            $re = json_decode($re);

            ///echo count($re);
            if (count($re) == 0) {
                $re['rsp'] = "error";
                $re['log'] = "error for no pic";

                return $re;
            } else {

                // var_dump($re);

                $pcimg = $this->change_imglist(json_decode($re->picimg));
                $mobile = $this->change_imglist(json_decode($re->mobile));
                $info = $this->change_imglist(json_decode($re->info));
                $thumb = json_decode($re->thumb);
                $thumb = 'http://' . $thumb[0];
                $re2 = '';
                $re2['rsp'] = 'succ';
                $re2['info_pc'] = $pcimg;
                $re2['info_mobile'] = $mobile;
                $re2['pic_list'] = $info;
                $re2['pic_thumb'] = $pcimg;

                ///M('goods')->where('id='.$goods['id'])->data($data)->save();
                ///var_dump($re2);
                return $re2;
            }
        }
    }

    ////获取并写入
    function get_goods_img($goods_id) {

        $goods = $this->init_goods($goods_id);

        //  $goods['sku']='P0042107  ';
        if (!$goods['sku']) {
            return array(
                'rsp' => 'error',
                'log' => 'sku 为空',
            );
        }
        $imgurl = "http://img01.shenghuigo.com/i.php?p=" . $goods['sku'];
        //echo $imgurl."<br>";
        //$ha=new \Qwadmin\Model\ApiModel();
        //$parm='';
        //$re=$ha->post($imgurl,$parm,60);

        $re = file_get_contents($imgurl);

        //echo $goods['sku']."-";
        if ($re == false || $re == '[]' || $re == 'false') {
            //$this->get_goods_img($goods_id);
            $re['rsp'] = 'error';
            $re['log'] = 'timeout_error :by network';
        } else {
            $re = json_decode($re);

            //echo count($re);
            if (count($re) == 0) {
                $re['rsp'] = "error";
                $re['log'] = "error for no pic";
            } else {

                $pcimg = $this->change_imglist(json_decode($re->picimg));
                $mobile = $this->change_imglist(json_decode($re->mobile));
                $info = $this->change_imglist(json_decode($re->info), 2);
                ///var_dump($info);
                $thumb = json_decode($re->thumb , true);
                $thumb = 'http://' . $thumb[0];

                $data['info_pc'] = $pcimg;
                $data['info_mobile'] = $mobile;
                $data['pic_list'] = json_encode($info);
                $data['pic_thumb'] = $thumb;

                $status = $this->where('id=' . $goods['id'])->save($data);

                $re = array();
                $re['rsp'] = "succ";
                $re['log'] = "ok";
                // echo $goods['sku'];
            }
        }
        return $re;
    }

    function update_goods($goods_id) {

        $goods = $this->init_goods($goods_id);

        if (count($goods['op'])) {
            $op = $goods['op'];

            foreach ($op as $k => $p) {


                if ($p['op'] == 'ADDNEW' && ($p['rsp'] != 'succ' && $p['rsp'] != 'error')) {
                    //echo "xxxxxx".$p['rsp'];
                    $shopsiteapi = new \Qwadmin\Controller\ShopSiteApiController();
                    $shopsiteapi->addnewgoods($p['goods_id'], $p['site_id'], $p['store_id']);
                }
            };
        } else {
            echo json_encode(array(array('rsp' => 'err'), array('err' => '暂时没有需要操作的上传的产品')));
        };
    }

    function checkgoodsaddnew() {
        set_time_limit(0);
        $per = 20;
        $page = 0;

//        $fileds='id,name,sku,goods_brand_id,price_market,price_cost,price,price_trade,made_in,info_pc,info_mobile,info_notice,';
        do {
            $res = $this->limit($page * $per . ",{$per}")->select();
            foreach ($res as $key => $value) {
                $this->checkgoods($value);
            }
            $page++;
            echo "正在处理第 {$page} 页数据 \n\r <br>";
        } while (count($res) == $per);
        echo "共：$page 页 已处理";
    }

    function checkgoods($value) {
        ////检测单条商品的数据是否能够更新到服务器上
        $updata = array(
            'pic_info_num' => 1, //商品banner
            'goods_id' => $value['id'], //商品banner
            'pic_thumb_num' => 1, //商品banner
            'pic_pc_num' => $this->getimgnum($value['info_pc']), //产品描述 pc
            'pic_mobile_num' => $this->getimgnum($value['info_mobile']), //产品描述 mo
            'price_ok' => 1, //商品价格设置与否  
            'info_ok' => 1, // 其他必填驻点是否满足
        );

        //检查是否设置价格
        if (!$value['price'] || !$value['price_cost'] || !$value['price_market'] || !$value['price_trade']) {
            $updata['price_ok'] = 0;
        }
        foreach ($this->goodscheckGonfig['oother_must_field'] as $must) {
            if (!$value[$must]) {
                $updata['info_ok'] = 0;
            }
        }
        $updata['can_new'] = $updata['info_ok'] ? 1 : 0;
        $goods_info_model = M("goods_info");
        if ($goods_info_model->where(array("goods_id" => $value['id']))->getField("goods_id")) {
            //存在 则更新
            $goods_info_model->where(array("goods_id" => $value['id']))->save($updata);
        } else {
            $goods_info_model->add($updata);
        }
        //返回商品状态
        return $updata['can_new'];
    }

    /*     * *
     * 检查是否是商品
     */

    function goodsimagecheck($url) {
        $pattern = sprintf("/(%s)/i", implode("|", $this->imageextarr));
        return preg_match($pattern, $url);
    }

    /**
     * 返回图片数量
     * @param type $str
     * @return type
     */
    function getimgnum($str) {
//        $count=0;
//        var_dump(substr_count($str,".jpg"));
//        
//        foreach ($this->imageextarr as $value) {
//            $count+=substr_count($str,$value);
//        }
//        echo $count;die;

        $pattern = sprintf("/(%s)/i", implode("|", $this->imageextarr));
//        $pattern="/(.png|.jpg)/i";
        preg_match_all($pattern, $str, $matches);
        return count($matches[0]);
    }

    function change_imglist($list, $type = 1) {
        $time = time();
        $str = '';
        sort($list, SORT_STRING);
        foreach ($list as $k => $v) {

            if ($type == 1) {
                if (strpos($v, 'http') == 0 && strpos($v, 'http') != false) {
                    $str.='<img src="' . $v . '?' . $time . '" class="img01' . strpos($v, 'http') . '">';
                } else {
                    $str.='<img src="http://' . $v . '?' . $time . '" class="img01">';
                }
            } else {

                return $list;
            }
        }

        return $str;
    }

    /**
     * 通过绑定商铺ID 和站点 获取网站的真实商铺ID
     * @param type $band_id
     * @param type $shop_id
     */
    function getRealStore_id($band_id, $shop_id = 10001) {
        $model = M("Partner_store");
        $storeId = $model->where(array('shop_id' => $shop_id, "bind_partner" => $band_id))->getField('store_id');
        return intval($storeId);
    }

    function gettradeid($code, $shop_id) {
        $model = M("trade");
        $storeId = $model->where(array('site_id' => $shop_id, "code" => $code))->getField('trade_id');
        return intval($storeId);
    }

    function getBrand_idBy_name($name) {
        $id = 1;
        $name = trim($name);
        $data = M('goods_brand')->where(array("name" => $name))->field("id")->find();
        if ($data) {
            $id = $data['id'];
        }
        return $id;
    }

    function getMadein_IDBy_name($name) {
        $id = 1;
        $name = trim($name);
        $data = M('country')->where(array("Chinese_name" => $name))->field("country_id")->find();
        if ($data) {
            $id = $data['country_id'];
        }
        return $id;
    }
    function gettrade_type_by_name($name) {
        $id = "N2";
        $name = trim($name);
        $data = M('trade')->where(array("name" => $name))->field("code")->find();
        if ($data) {
            $id = $data['code'];
        }
        return $id;
    }
    function getMade_in_list() {
       $tradeList = M('country')->cache(true,1000)->field('Chinese_name,English_name,country_id')->select();
        $temp=array();
        foreach($tradeList as $key=>$val){
            $temp[$val['country_id']]['Chinese_name'] = $val['chinese_name'];
            $temp[$val['country_id']]['English_name'] = $val['english_name'];
        }
        return $temp;
    }

}
